package exchange

import (
	"errors"
	"gpt-api/framework/auther"
	"gpt-api/framework/codes"
	"gpt-api/framework/db"
	"gpt-api/framework/ginplus"
	"gpt-api/pkg/model"

	"github.com/gin-gonic/gin"
)

type Handler struct {
	db     *db.DB
	auther auther.Auther
}

func New(db *db.DB, auther auther.Auther) *Handler {
	return &Handler{db: db, auther: auther}
}

// 兑换
func (h *Handler) ExchangeCode(c *gin.Context) error {
	// 获取用户id
	userId := ginplus.GetUserID(c)

	var req struct {
		Code string `json:"code" binding:"required"`
	}
	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	// fmt.Println("code:", req.Code)

	// 查询兑换码
	codeInfo, err := (&model.Exchange{}).GetExchangeCodeByCode(h.db, req.Code)
	// fmt.Println("codeInfo:", codeInfo.CodeStatus)
	// fmt.Println("err:", err)
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	// 兑换码状态
	if codeInfo.CodeStatus == 1 {
		return ginplus.ReplyError(c, codes.ExchangeCodeUsed, errors.New("兑换码已经使用过。"))
	}

	// 兑换
	err = (&model.Exchange{}).Ex(h.db, codeInfo.ID, userId)
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	// 返回兑换码信息
	codeInfo, err = (&model.Exchange{}).GetExchangeCodeByCode(h.db, req.Code)
	// fmt.Println("codeInfo:", codeInfo)
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	return ginplus.ReplyJSON(c, codeInfo)
}
